// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService;
using Microsoft.Security.Application;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks
{
    public partial class ManageNotificationSchedules : System.Web.UI.Page
    {
        List<NotificationSchedule> lstSchedules = new List<NotificationSchedule>();

        public void Page_Error(object sender, EventArgs e)
        {
            if (Server.GetLastError() is HttpException)
            {
                throw new HttpException(((HttpException)Server.GetLastError()).GetHttpCode(), Server.GetLastError().Message);
            }
            else
                throw new HttpException(500, "Unhandled Exception.");
        }


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskAdmin")))
                throw new HttpException(403, "Requires Task Administrator Role");

            if (ViewState["NotificationSchedules"] == null)
            {
                lstSchedules = new List<NotificationSchedule>();
                NotificationsServiceClient notClient = new NotificationsServiceClient();
                //if (User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                lstSchedules.AddRange(notClient.GetNotificationSchedules());
                //else if (User.IsInRole(Utility.GetConfigurationValue("TaskUser")))
                //    lstSchedules.AddRange(notClient.GetNotificationSchedulesByUser(((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId));
                ViewState["NotificationSchedules"] = lstSchedules;
                notClient.Close();
            }
            else
            {
                lstSchedules = (List<NotificationSchedule>)ViewState["NotificationSchedules"];
            }
            if (!Page.IsPostBack)
            {
                lblPageHeader.Text = "Manage Notification Schedules";
                this.DoDataBind();
            }
        }

        private void DoDataBind()
        {
            GridView1.DataSource = lstSchedules;
            GridView1.Columns[8].Visible = true;
            GridView1.DataBind();
            GridView1.Columns[8].Visible = false;
        }

        protected void btnAddNew_OnClick(object sender, EventArgs e)
        {
            createNotificationSchedule.HeaderText = "Create Notification Schedule";
            createNotificationSchedule.NotificationSchedule = new NotificationSchedule();
            createNotificationSchedule.NotificationSchedule.Notifications = new Notification[] { };
            createNotificationSchedule.IsEditing = false;
            createNotificationSchedule.ClearControls();
            mpeSchedule.Show();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            createNotificationSchedule.NotificationSchedule = new NotificationSchedule();
            createNotificationSchedule.ClearControls();
            mpeSchedule.Hide();
        }
        protected void btnScheduleSave_Click(object sender, EventArgs e)
        {
            try
            {
                createNotificationSchedule.Save();

                if (createNotificationSchedule.IsEditing)
                {
                    int index=0;
                    for (index = 0; index < lstSchedules.Count; index++) 
                    {
                        if (lstSchedules[index].ID == createNotificationSchedule.NotificationSchedule.ID)
                        {
                            break;
                        }
                    }
                    lstSchedules[index] = createNotificationSchedule.NotificationSchedule;
                }
                else
                    lstSchedules.Add(createNotificationSchedule.NotificationSchedule);
                this.DoDataBind();
                mpeSchedule.Hide();
            }
            catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
            {
                if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                {
                    Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                }
                else
                    Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_SAVE_UNKWNERR"), "Error", true);
            }
            catch 
            {
                Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_SAVE_UNKWNERR"), "Error", true);
            }
        }

        protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                foreach (System.Web.UI.Control BaseControl in e.Row.Cells[1].Controls)
                {
                    if (BaseControl.GetType().BaseType == typeof(LinkButton))
                    {
                        LinkButton linkBtn = (LinkButton)BaseControl;
                        if (linkBtn.CommandName == "Delete")
                        {
                            if (int.Parse(e.Row.Cells[5].Text) > 0)
                                linkBtn.OnClientClick = "alert('" + Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_DEL_ERR",4) + "'); return false;";
                            else
                                linkBtn.OnClientClick = "return confirm('" + Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_DEL_CONFIRM",4) + "');";
                        }
                    }
                }
            }
        }



        protected void GridView1_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int scheduleID = int.Parse(GridView1.Rows[e.RowIndex].Cells[8].Text);
            if (scheduleID > 0)
            {
                NotificationSchedule schedule = null;
                foreach (NotificationSchedule schedule1 in lstSchedules)
                {
                    if (schedule1.ID == scheduleID)
                    {
                        schedule = schedule1;
                        break;
                    }
                }
                if (schedule != null)
                {
                    NotificationsServiceClient notClient = new NotificationsServiceClient();
                    try
                    {
                        notClient.DeleteNotificationSchedule(scheduleID, ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId);
                        lstSchedules.Remove(schedule);
                        ViewState["NotificationSchedules"] = lstSchedules;
                        this.DoDataBind();
                    }
                    catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
                    {
                        if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                        {
                            Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                        }
                        else
                            Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_SAVE_UNKWNERR"), "Error", true);
                    }
                    catch
                    {
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_SAVE_UNKWNERR"), "Error", true);
                    }
                    notClient.Close();
                }
            }
            DoDataBind();
        }

        protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["GridSortDirection"] != null)
                if (ViewState["GridSortDirection"].ToString() == SortDirection.Ascending.ToString())
                    e.SortDirection = SortDirection.Descending;
                else
                    e.SortDirection = SortDirection.Ascending;

            lstSchedules.Sort(new NotificationScheduleComparer(e.SortDirection, e.SortExpression));

            ViewState["GridSortDirection"] = e.SortDirection;
            ViewState["GridSortExpression"] = e.SortExpression;
            this.DoDataBind();
        }

        protected void GridView1_OnRowEditing(object sender, GridViewEditEventArgs e)
        {

            int scheduleID = int.Parse(GridView1.Rows[e.NewEditIndex].Cells[8].Text);
            if (scheduleID > 0)
            {
                NotificationSchedule schedule = null;
                try
                {
                    createNotificationSchedule.HeaderText = "Edit Notification Schedule";
                    NotificationsServiceClient notClient = new NotificationsServiceClient();
                    
                    schedule = notClient.GetNotificationSchedule(scheduleID);
                    if (schedule != null)
                    {
                        createNotificationSchedule.NotificationSchedule = schedule;
                        createNotificationSchedule.IsEditing = true;
                        mpeSchedule.Show();
                    }
                    notClient.Close();
                }
                catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
                {
                    if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                    {
                        Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                    }
                    else
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_LOAD_UNKWNERR"), "Error", true);
                }
                catch
                {
                    Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_LOAD_UNKWNERR"), "Error", true);
                }
            
            }

        }

        protected void btnMakeDefault_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "MakeDefault")
            {
                int scheduleID = 0;
                int.TryParse(e.CommandArgument.ToString(), out scheduleID);
                if (scheduleID > 0)
                {
                    try
                    {
                        NotificationsServiceClient notClient = new NotificationsServiceClient();
                        notClient.SetDefaultNotificationSchedule(scheduleID, Utility.GetUserFullName(),((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId);
                        notClient.Close();
                        foreach (NotificationSchedule ns in this.lstSchedules) 
                        {
                            if (ns.ID == scheduleID)
                            {
                                ns.IsDefault = true;
                                ns.LastUpdatedDate = DateTime.UtcNow;
                                ns.LastUpdatedBy = Utility.GetUserFullName();
                            }
                            else
                            {                                
                                // Only update the record which was default earlier.
                                if ((ns.ID != scheduleID) && (ns.IsDefault == true))
                                {
                                    ns.LastUpdatedDate = DateTime.UtcNow;
                                    ns.LastUpdatedBy = Utility.GetUserFullName();
                                }
                                ns.IsDefault = false;
                            }
                        }
                        this.DoDataBind();
                        
                    }
                    catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
                    {
                        if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                        {
                            Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                        }
                        else
                            Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_LOAD_UNKWNERR"), "Error", true);
                    }
                    catch
                    {
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_LOAD_UNKWNERR"), "Error", true);
                    }
                }
            }
        }

    }

    class NotificationScheduleComparer : IComparer<NotificationSchedule>
    {
        SortDirection sortDir = SortDirection.Ascending;
        string sortExpr = "";
        public NotificationScheduleComparer(SortDirection sortDirection, string sortExpression)
        {
            sortDir = sortDirection;
            sortExpr = sortExpression;
        }

        public int Compare(NotificationSchedule x, NotificationSchedule y)
        {
            switch (sortExpr)
            {
                case "Name":
                    if (sortDir == SortDirection.Ascending)
                        return StringComparer.CurrentCultureIgnoreCase.Compare(x.Name, y.Name);
                    else
                        return StringComparer.CurrentCultureIgnoreCase.Compare(y.Name, x.Name);
                case "LastUpdatedBy":
                    if (sortDir == SortDirection.Ascending)
                        return StringComparer.CurrentCultureIgnoreCase.Compare(x.LastUpdatedBy, y.LastUpdatedBy);
                    else
                        return StringComparer.CurrentCultureIgnoreCase.Compare(y.LastUpdatedBy, x.LastUpdatedBy);
                case "LastUpdatedDate":
                    if (sortDir == SortDirection.Ascending)
                        return DateTime.Compare(x.LastUpdatedDate, y.LastUpdatedDate);
                    else
                        return DateTime.Compare(y.LastUpdatedDate, x.LastUpdatedDate);
                case "TaskCount":
                    if (sortDir == SortDirection.Ascending)
                        if (x.TaskCount > y.TaskCount)
                            return 1;
                        else if (x.TaskCount < y.TaskCount)
                            return -1;
                        else
                            return 0;
                    else
                        if (y.TaskCount > x.TaskCount)
                            return 1;
                        else if (y.TaskCount < x.TaskCount)
                            return -1;
                        else
                            return 0;
                case "IsDefault":
                    if (sortDir == SortDirection.Ascending)
                        if (x.IsDefault==true && y.IsDefault==false)
                            return 1;
                        else if (x.IsDefault == false && y.IsDefault == true)
                            return -1;
                        else
                            return 0;
                    else
                        if (x.IsDefault==false && y.IsDefault==true)
                            return 1;
                        else if (x.IsDefault == true && y.IsDefault == false)
                            return -1;
                        else
                            return 0;
            }
            return 0;
        }

        
    }
}
